import { http } from "@/utils/http";

type Result = {
  success: boolean;
  data: Array<any>;
};

export const getAsyncRoutes = () => {
  // return http.request<Result>("get", "/get-async-routes").then(result => {
  //   console.log(result);
  //   return result;
  // });
  return http
    .request<Result>(
      "get",
      import.meta.env.VITE_API + "/api/AdminModule/SysMenu/GetUserRoute"
    )
    .then(result => {
      console.log("getAsyncRoutes api", result.data);
      result.data = convertToRouteRecordRaw(result.data);
      return result;
    });
};

function convertToRouteRecordRaw(
  data: Array<any>,
  parentId = "00000000-0000-0000-0000-000000000000"
): Array<any> {
  return data
    .sort((a, b) => a.sort - b.sort)
    .filter(e => e.parentId == parentId)
    .map(item => {
      const { path, name, component, redirect, permission } = item;
      let meta = {
        backstage: true,
        auths: permission,
        // rank: sort,
        // roles: ["admin"],
        ...item
      };
      let children = data.filter(e => e.parentId == item.id);
      return {
        path,
        name,
        component,
        redirect,
        meta,
        children: children.length
          ? convertToRouteRecordRaw(data, item.id)
          : undefined
      };
    });
}
